package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    //注入用户dao
    @Autowired
    private UserDao userDao;

    @Autowired
    //注入角色dao
    private RoleDao roleDao;

    @Autowired
    //注入权限dao
    private PermissionDao permissionDao;

    @Override
    public User findUserByUsername(String username) {
        User user = userDao.findUserByUsername(username);
        if(user == null){
            return null;
        }

        //通过用户的id查询权限
        Integer userId = user.getId();
        //通过userId查询角色(1或多个角色)

        Set<Role> roles = roleDao.findRolesByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //通过roleId查询对应的1个或多个权限
            Set<Permission> permissions = permissionDao.findPermissionsByRoleId(roleId);
            role.setPermissions(permissions);
        }

        user.setRoles(roles);
        return user;
    }

    @Override
    public String findUserPortraitByUsername(String username) {
        return userDao.findUserPortraitByUsername(username);
    }

    @Override
    public List<Map<String, Object>> findMenu() {
        return userDao.findMenu();
    }

    @Override
    public List<Map<String, Object>> findMenuById(Integer id) {
        return userDao.findMenuById(id);
    }
}
